<template>
	<div class="app-container">
		<comprehensive-table @selection-change="selectionChange" :columns="column" :data="data" @reset="reset" @onSubmit="onSubmit" @getPageSize='getPageSize'>
			<!-- 表格按顺序排列，先是data部分，然后是文章封面图片，最后是添加删除操作按钮-->
			<template v-slot:btn>
				<div style="display: flex;justify-content: flex-end">
					<el-button type="primary" @click="add"><i class="el-icon-circle-plus icon"></i> 添加</el-button>
					<el-button type="danger" @click="batchDelete"><i class="el-icon-delete icon"></i>删除</el-button>
				</div>
			</template>

			<!-- v-slot:列名的名字name  文章封面和内容-->
			<template v-slot:images='scope'>
				<img :src="getImage(scope.row.images)" style="width:100%;height: aoto;" />
			</template>
			<template v-slot:content='scope'>
				<text class="content">
					{{scope.row.content}}
				</text>
				<el-button type="text" @click="isExpand=!isExpand;openDialog(scope.row)">展开</el-button>
			</template>

			<template v-slot:operation="scope">
				<el-button type="primary" size="small" icon="Edit" @click="edit(scope.row)">
					<i class="el-icon-edit icon"></i>
					编辑
				</el-button>
				<el-button @click="del(scope.row)" type="danger" size="small" icon="Delete">
					<i class="el-icon-delete icon"></i>
					删除
				</el-button>
			</template>
		</comprehensive-table>

		<!-- 表格中文章内容点击 展开 按钮 -->
		<el-dialog :visible.sync="isExpand" title="文章内容" style="top:30%">
			<text>{{selectedRowData.content}}</text>
		</el-dialog>

		<!-- 点击添加和编辑弹出的对话框 -->
		<el-dialog :visible.sync="dialogVisible" :title="title" width="50%">

			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
				:size="formSize">
				<el-form-item label="文章标题" prop="name">
					<el-input v-model="ruleForm.name" />
				</el-form-item>
				<el-form-item label="文章类型" prop="categoryName">
					<el-radio-group v-model="ruleForm.categoryName">
						<el-radio :label="1">新闻咨询</el-radio>
						<el-radio :label="2">热门话题</el-radio>
						<el-radio :label="3">回收攻略</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="发布来源" prop="author">
					<el-input v-model="ruleForm.author" />
				</el-form-item>
				<el-form-item label="发布时间" prop="createTime">
					<el-input v-model="ruleForm.createTime" />
				</el-form-item>
				<el-form-item label="上次修改时间" prop="modifyTime">
					<el-input v-model="ruleForm.modifyTime" />
				</el-form-item>

				<el-form-item label="文章封面" prop="images">
					<!-- 点击编辑按钮 -->
					<view v-if="isFileUpload==false">
						<img :src="getImage(ruleForm.images)" v-model="ruleForm.images" style="width: 70%;border-radius: 10px;"></img>
						<el-upload class="upload-demo" 
							action="http://43.136.172.73/api/v1/system/upload/files/"
							:auto-upload='false' :on-success="modifyPicture" list-type="picture">
							<el-button size="small" type="primary">点击修改</el-button>
						</el-upload>

					</view>


					<!-- 点击添加按钮上传文件 -->
					<el-upload v-if="isFileUpload==true" drag ref="imageUpload"
						action="http://43.136.172.73/api/v1/system/upload/files" multiple :auto-upload='true'
						list-type="picture" :on-success="handleSuccess" style="width: 70%;">
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						<div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>

				</el-form-item>

				<el-form-item label="文章内容" prop="content">
					<div>
						<vue-editor v-model="ruleForm.content" @image-added="uploadImage"></vue-editor>
					</div>
				</el-form-item>

			</el-form>

			<!-- 对话框下面的取消确定按钮 -->
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleClose('ruleFormRef')">确定</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script>
	var dayjs = require('dayjs')
	// 富文本编辑器
	import {
		VueEditor
	} from 'vue2-editor'
	import {
		Card
	} from 'element-ui'

	import findingApi from '../../common/finding/FindingApi'
	import ComprehensiveTable from './components/comprehensive.vue'
	const data = []

	const column = [{
			type: 'selection',
			width: 60
		},
		{
			name: 'id',
			label: 'id',
			width: 50,
		},
		{
			name: 'name',
			label: '标题',
			//inSearch为true 会出现在最上面
			inSearch: true,
			// 有查询搜索框
			valueType: 'input',
			width: 150
		},
		{
			name: 'categoryName',
			label: '文章类型',
			inSearch: true,
			options: [{
				value: 1,
				label: '新闻咨询'
			}, {
				value: 2,
				label: '热门话题'
			}, {
				value: 3,
				label: '回收攻略'
			}],
			valueType:'select',
			
		},
		{
			name: 'author',
			label: '发布来源',
			inSearch: true,
			valueType: 'input',
		},
		{
			name: 'createTime',
			label: '发布时间',

		},
		{
			name: 'modifyTime',
			label: '上次修改时间',
		},
		{
			name: 'visitors',
			label: '访问量',
		},

		// 文章内容
		{
			name: 'images',
			label: '文章封面',
			slot: true,

		},
		{
			name: 'content',
			label: '文章内容',
			width: 300,
			slot: true,
		},


		{
			name: 'operation',
			label: '操作',
			slot: true,
			fixed: 'right',
			width: 200
		}
	]



	export default {
		components: {
			ComprehensiveTable,
			VueEditor,

		},

		data() {
			return {
				data,
				column,
				formSize: 'default',
				dialogVisible: false,
				title: '新增',
				rowObj: {},
				selectObj: [],
				ruleForm: {
					name: '',
					categoryName: null,
					author: '',
					createTime: '',
					modifyTime: '',
					images: '',
					content: ''
				},
				rules: {
					name: [{
						required: true,
						message: '请输入文章标题',
						trigger: 'blur'
					}],
					author: [{
						required: true,
						message: '请输入发布来源',
						trigger: 'blur'
					}],
					content: [{
						required: true,
						message: '请输入文章内容',
						trigger: 'blur'
					}],


				},
				pageSize: '10',
				isExpand: false,
				selectedRowData: '', //被选中行的数据
				isFileUpload: true, //是否上传文件
			}
		},
		mounted() {
			// 加载文章表格
			this.listArticles()

		},
		methods: {
			// 点击编辑按钮上传图片
			modifyPicture(response, file, fileList) {
				console.log(response)
			},

			//点击对话框确定按钮后，先上传图片返回一个路径，在根据这个路径上传文章内容
			handleSuccess(response) {
				console.log(response)
			},

			// 对话框的确认按钮
			async handleClose(formName) {
				// 对整个表单进行自检，返回回调函数。自检正确valid为true
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (valid) {
							// 文章对象
							let obj = {
								// id:Date.now(),
								// 使用了对象展开操作符 ...，将 this.ruleForm 对象中手动输入的所有属性和值复制到 obj 中
								...this.ruleForm,
							}
							// 添加文章对话框
							if (this.title === '新增') {
								// 将一个对象 obj 添加到数组 this.data 的前面，在开头添加
								this.data = [obj, ...this.data]
								
								/**发添加请求*/
								findingApi.articleAdd({obj}).then(res => {
									console.log('添加成功', res)
									this.$message.success('添加成功')
								})
							}
							
							// 编辑文章对话框
							else {
								//使用 forEach 方法遍历数组 this.data 中的每个元素，然后检查每个元素的 id 是否与 this.rowObj.id 相匹配。如果找到匹配的元素，它会更新该元素的属性，将其值从 obj 对象中获取。
								this.data.forEach(item => {
									if (item.id === this.rowObj.id) {
										item.name = obj.name
										item.categoryName = obj.categoryName
										item.author = obj.author
										item.createTime = obj.createTime
										item.modifyTime = obj.modifyTime
										item.images = obj.images
										item.content = obj.content
										
										/** 发更新请求*/
										let params={obj}
										findingApi.updateArticle(params).then(res=>{
											console.log('更新成功',res)
										})
									}
								})

							}
							this.dialogVisible = false
							console.log('submit!', obj)
						} else {
							console.log('error submit!', fields)
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			// 动态获取图片
			getImage(image) {
				return `http://43.136.172.73/api/v1/file/download?fileName=${image}`
			},
			// 点击展开按钮打开对话框
			openDialog(row) {
				this.selectedRowData = row; // 存储被选中行的数据
			},
			listArticles() {
				let params = {
					currentPage: 1,
					pageSize: this.pageSize
				}
				findingApi.queryFindingArticleList(params).then(res => {
					console.log('后台查询全部文章内容', res.data.data.records);
					this.data = res.data.data.records
					for (var i = 0; i < this.data.length; i++) {
						console.log(this.data[i].createTime)
						this.data[i].createTime = this.data[i].createTime.split('T')[0]
						this.data[i].modifyTime = this.data[i].modifyTime.split('T')[0]
						console.log(this.data[i].createTime)
					}

				})
			},
			// 新增文章
			add() {
				this.title = '新增'
				this.dialogVisible = true
				this.isFileUpload = true
				// 点击编辑后再点添加，不会传值过去
				this.ruleForm.name = ''
				this.ruleForm.categoryName = 1,
				this.ruleForm.author = ''
				this.ruleForm.createTime = ''
				this.ruleForm.modifyTime = ''
				this.ruleForm.content = ''


			},
			// 删除文章（可以选中多个或一个）
			batchDelete() {
				if (!this.selectObj.length) {
					return this.$message.error('未选中任何行')
				}
				this.$confirm(
						'你确定要删除选中项吗?',
						'温馨提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
							draggable: true,
						}
					)
					.then(() => {

						this.$message.success('模拟删除成功')
						this.data = this.data.concat([])
					})
					.catch(() => {

					})
			},

			selectionChange(val) {
				this.selectObj = val
			},

			edit(row) {
				this.title = '编辑'
				this.rowObj = row
				this.dialogVisible = true
				this.ruleForm.name = row.name
				this.ruleForm.categoryName = row.categoryName,
				this.ruleForm.author = row.author
				this.ruleForm.createTime = row.createTime
				this.ruleForm.modifyTime = row.modifyTime
				this.ruleForm.images = row.images
				this.ruleForm.content = row.content
				this.isFileUpload = false
			},
			// 编辑后面的删除按钮（一次只能删除一个记录）
			del(row) {
				this.$confirm(
						'你确定要删除当前项吗?',
						'温馨提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
							draggable: true,
						}
					)
					.then(() => {
						// filter()用于把数组的某些元素的筛选，然后返回剩下的元素。filter()也接收一个数组
						//它会检查数组中的每个元素。对于每个元素 item, 它将检查 item 的 id 属性是否不等于 row 的 id 属性。如果条件成立（true），则元素将包含在新数组中，否则将被过滤掉。
						this.data = this.data.filter(item => item.id !== row.id)
						let params={id:row.id}
						findingApi.removeArticle(params).then(res => {
							console.log('删除成功',res)
							this.$message.success('删除成功')
						})
					})
					.catch(() => {
						this.$message.success('删除失败')
					})
			},

			reset() {
				this.$message.success('触发重置方法')
			},
			/**模糊查询*/
			onSubmit(e) {
				let params={
					title:e.name,
					pageSize:this.pageSize,
					currentPage:1
					}
				findingApi.queryByTitleOrAuthor(params).then(res=>{
					console.log('根据标题模糊查询：',res)
					this.data=res.data.data.records
					for (var i = 0; i < this.data.length; i++) {
						this.data[i].createTime = this.data[i].createTime.split('T')[0]
						this.data[i].modifyTime = this.data[i].modifyTime.split('T')[0]
					}
				})
			},
			getPageSize(pageSize) {
				this.pageSize = pageSize
				console.log('获取到子组件传参-页面大小：', pageSize)
				// 点击每页显示多少条数据后再显示
				this.listArticles()
			}

		}
	}
</script>
<style scoped>
	.edit-input {
		padding-right: 100px;
	}

	.cancel-btn {
		position: absolute;
		right: 15px;
		top: 10px;
	}

	.icon {
		margin-right: 4px;
	}


	.content {
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 3;
		overflow: hidden;
	}
</style>